package com.just.login.dao;

import com.just.login.Model.User;
import com.just.login.annotations.component;

import java.io.*;
import java.util.*;

@component
public class Userdao {

    // 获取用户列表添加到Hash
    public HashMap<String, String> getUserlist() {
        HashMap<String , String > map = new HashMap<>();
        List<User> userList = new ArrayList<>();
        try(BufferedReader in = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("database/database.txt")))){
            while (in.ready()) {
                String line = in.readLine();
                System.out.println(line);
                String[] cell = line.split(", ");
                map.put(cell[0], cell[1]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    // 根据用户名查找用户
    public User getUserByAccount(String account) {
        List<User> userList = getUserList();
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            if (user.getUsername().equals(account)) {
                return user;
            }
        }
        return null;
    }

    // 新增用户
    public boolean InsertUser(User user) {
        String path = getClass().getClassLoader().getResource("database/database.txt").getPath();
        try(BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path, true)))){
            StringBuffer info = new StringBuffer();
            info.append(user.getUsername());
            info.append(", ");
            info.append(user.getPassword());
            info.append(", ");
            info.append(user.getSalt());
            out.write(info.toString());
            out.flush();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    // 根据用户名查询所有用户
    public List<User> getUserList() {
        List<User> userList = new ArrayList<>();
        try(BufferedReader in = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("database/database.txt")))){
            while (in.ready()) {
                String line = in.readLine();
                System.out.println(line);
                String[] cell = line.split(", ");
                userList.add(new User(cell[0], cell[1], cell[2]));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return userList;
    }
}
